package ui.finance;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import javax.swing.JPanel;

import tool.LongStringTransformer;
import tool.MyButton;
import tool.MyLabel;
import vo.AccountorVo;
import vo.Vo;
import vo.UserVo;
import vo.条目清单单项vo;
import vo.CashExpensesDocumentVo;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import client.boot.BLServiceManager;
import blservice.document.DocumentBLService;
import blservice.finance.AccountorBLService;

import java.awt.Font;
import java.awt.Color;

public class 现金费用单Panel extends JPanel {
	private static final long serialVersionUID = 2586353259038592152L;

	DocumentBLService documentsBL;

	CashExpensesDocumentVo vo;
	UserVo user;
	private JComboBox<String> account;
	private JTable table;
	private JScrollPane jsp;
	private JTextField number;
	private JTextField operator;
	private JTextField sum;
	private boolean isNew;
	private boolean editable;
	private Vector<String> accountNames;
	private boolean 审批;
	private boolean 红冲;

	/**
	 * 
	 * @param user
	 * @param vo
	 *            如果是单据查询，则传入vo，如果是单据制定则传入null;
	 * @param editable
	 *            如果是新建或者红冲并复制就设置成editable
	 * @param 红冲 
	 */
	public 现金费用单Panel(UserVo user, CashExpensesDocumentVo vo, boolean editable,boolean 审批, boolean 红冲) {
		this.红冲=红冲;
		this.审批=审批;
		this.user = user;
		this.setLayout(null);
		this.setOpaque(false);
		this.editable = editable;
		if (vo == null) {
			isNew = true;
			this.vo = new CashExpensesDocumentVo();
		} else {
			isNew = false;
			this.vo=vo;
		}
		JLabel label = new JLabel("现金费用单制定");
		label.setForeground(Color.WHITE);
		label.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		label.setBounds(249, 10, 173, 21);
		add(label);

		JLabel label_1 = new MyLabel("\u5355\u636E\u7F16\u53F7\uFF1A");
		label_1.setBounds(47, 53, 75, 15);
		add(label_1);

		JLabel label_2 = new MyLabel("银行账户：");
		label_2.setBounds(47, 78, 75, 15);
		add(label_2);

		account = new JComboBox<String>();
		account.setBounds(122, 75, 105, 21);	
		add(account);

		JLabel label_3 = new MyLabel("\u8F6C\u8D26\u5217\u8868");
		label_3.setBounds(47, 100, 54, 15);
		add(label_3);

		JButton add = new MyButton("Graphics/Button45-23.png");
		add.setText("+");
		add.setBounds(465, 96, 45, 23);
		if (!editable) {
			add.setVisible(false);
		}
		add.addActionListener(e->addLine());
		add(add);

		JLabel label_4 = new MyLabel("业务员：");
		label_4.setForeground(Color.WHITE);
		label_4.setBounds(370, 53, 54, 15);
		add(label_4);

		JLabel label_5 = new MyLabel("\u603B\u989D\uFF1A");
		label_5.setBounds(47, 387, 54, 15);
		add(label_5);

		JButton submit = new MyButton("Graphics/Button93-23.png");
		submit.setText("\u63D0\u4EA4");
		submit.setBounds(489, 383, 93, 23);
		submit.addActionListener(e->submit());
		if (!editable&&!审批&&!红冲) {
			submit.setVisible(false);
		}
		if(审批){
			submit.setText("通过审批");
		}
		if(红冲){
			submit.setText("红冲");
		}
		add(submit);

		JButton sub = new MyButton("Graphics/Button45-23.png");
		sub.setText("-");
		sub.setBounds(537, 96, 45, 23);
		sub.addActionListener(e->subLine());
		if (!editable) {
			sub.setVisible(false);
		}
		add(sub);

		table = new JTable() {
			private static final long serialVersionUID = 3028897666676861555L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return editable;
			}
		};
		table.setBounds(47, 128, 535, 248);
		jsp = new JScrollPane(table);
		jsp.setBounds(47, 128, 535, 248);
		jsp.setVisible(true);
		this.add(jsp);

		number = new JTextField();
		number.setEditable(false);
		number.setColumns(10);
		number.setBounds(122, 50, 105, 21);
		add(number);

		operator = new JTextField();
		operator.setEditable(false);
		operator.setColumns(10);
		operator.setBounds(429, 50, 105, 21);
		if (isNew) {
			operator.setText(user.getName());
		} else {
			operator.setText(vo.get业务员());
		}
		add(operator);

		sum = new JTextField();
		sum.setEditable(false);
		sum.setBounds(122, 384, 105, 21);
		add(sum);
		sum.setColumns(10);

		iniAccount();
		
		if (isNew) {
			this.vo.set单据编号("");
			this.vo.set业务员(user.getName());
		}
		display();
	}

	void display() {
		number.setText(vo.get单据编号());
		operator.setText(vo.get业务员());
		account.setSelectedItem(vo.get银行账户());
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "条目名", "金额", "备注" });
		
		for (条目清单单项vo o : vo.get条目清单()) {
			model.addRow(new String[] { o.get条目名(),
					tool.LongStringTransformer.LongToString(o.get金额()),
					o.get备注() });
			
		}		
		if (editable) {			
			model.addRow(new String[] {"", "", "" });
		}
		table.setModel(model);
		this.sum.setText(LongStringTransformer.LongToString(vo.get总额()));
	}

	void save() {
		vo.set业务员(user.getName());
		vo.set银行账户((String) account.getSelectedItem());
		List<条目清单单项vo> items=vo.get条目清单();
		items.clear();
		long total=0;
		for(int i=0;i<table.getRowCount();i++){
			条目清单单项vo temp=new 条目清单单项vo();
			temp.set备注((String)table.getValueAt(i, 2));
			temp.set条目名((String)table.getValueAt(i, 0));
			boolean successed=false;
			
			try{
				long tempMoney=LongStringTransformer.StringToLong((String)table.getValueAt(i, 1));
				temp.set金额(tempMoney);
				successed=true;
				
			}catch(NumberFormatException e){
			}
			if(successed){
				total=total+temp.get金额();
				items.add(temp);
			}
		}
		vo.set总额(total);
	}
	
	void subLine(){
		int line=table.getSelectedRow();
		if(line==-1||line>=vo.get条目清单().size()){
			return;
		}else{
			vo.get条目清单().remove(line);
			display();
		}
	}

	void addLine() {
		save();
		display();
	}
	
	void submit(){
		save();
		display();
		if(vo.get条目清单().size()==0){
			JOptionPane.showMessageDialog(this,
					"请填写条目清单\n");
			return;
		}
		DocumentBLService bl;
		try {
			bl = BLServiceManager.load现金费用单BLService(null);
			vo.setOperation("添加现金费用单");
			vo.setOperator(user.getName());
			Vo result;
			if(审批){
				result=bl.approve(vo);
			}else if(红冲&&!editable){
				result=bl.redRush(vo);
			}else if(红冲&&editable){
				result=bl.redRushAndCopy(vo);
			}else{				
				result = bl.add(vo);
			}
			if(result.isSuccessed()){
				JOptionPane.showMessageDialog(this,
						"单据提交成功\n");
				vo=new CashExpensesDocumentVo();
				display();
			}else{
				JOptionPane.showMessageDialog(this,
						"单据提交失败\n"+result.getFailMessage());
			}
		} catch (RemoteException | MalformedURLException | SQLException
				| NotBoundException e) {
			JOptionPane.showMessageDialog(this,
					"无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}
		
	}
	
	void iniAccount(){
			try {
				AccountorBLService clientBL = BLServiceManager
						.getAccountorBLService(null);
				List<AccountorVo> accounts = clientBL.getAll();
				accountNames = new Vector<String>();
				for (AccountorVo o : accounts) {
					accountNames.add(o.get名称());
				}
				account.setModel(new DefaultComboBoxModel<String>(accountNames));
				account.setEnabled(editable);
			} catch (RemoteException | MalformedURLException
					| NotBoundException | SQLException e) {
				JOptionPane.showMessageDialog(this,
						"无法连接到服务器\n" + e.getMessage());
				e.printStackTrace();
			}
		
	}
}
